<template>
  <div class="side-nav" :class="{'collapsed': !showText, 'mobile-hidden': isMobile && !showText, 'mobile-visible': isMobile && showText}">
    <el-menu
      :default-active="activeMenuName"
      router
      active-text-color="#2196f3"
      text-color="#495060"
      background-color="#f8f9fa"
      class="el-menu-vertical"
      :collapse="!showText"
      @select="handleMenuSelect"
      style="top: 60px;"
    >
      <el-menu-item index="/problem">
        <i class="el-icon-s-grid"></i>
        <span>{{ $t('m.NavBar_Problem') }}</span>
      </el-menu-item>

      <el-menu-item index="/training">
        <i class="el-icon-s-claim"></i>
        <span>{{ $t('m.NavBar_Training') }}</span>
      </el-menu-item>

      <el-menu-item index="/contest">
        <i class="el-icon-trophy"></i>
        <span>{{ $t('m.NavBar_Contest') }}</span>
      </el-menu-item>

      <el-menu-item index="/status">
        <i class="el-icon-s-marketing"></i>
        <span>{{ $t('m.NavBar_Status') }}</span>
      </el-menu-item>



      <el-menu-item index="/discussion" v-if="websiteConfig.openPublicDiscussion">
        <i class="el-icon-s-comment"></i>
        <span>{{ $t('m.NavBar_Discussion') }}</span>
      </el-menu-item>

      <el-menu-item index="/group">
        <i class="fa fa-users navbar-icon"></i>
        <span>{{ $t('m.NavBar_Group') }}</span>
      </el-menu-item>

      <el-menu-item index="#course" @click="openCourse">
        <i class="el-icon-reading"></i>
        <span>{{ $t('m.Course') }}</span>
      </el-menu-item>

      <el-submenu index="rank" popper-class="always-popup">
        <template slot="title">
          <i class="el-icon-s-data"></i>
          <span>{{ $t('m.NavBar_Rank') }}</span>
        </template>
        <el-menu-item index="/acm-rank">{{ $t('m.NavBar_ACM_Rank') }}</el-menu-item>
        <el-menu-item index="/oi-rank">{{ $t('m.NavBar_OI_Rank') }}</el-menu-item>
      </el-submenu>

      <el-submenu index="#tool" popper-class="always-popup">
        <template slot="title">
          <i class="el-icon-setting"></i>
          <span>{{ $t('m.NavBar_Tool') }}</span>
        </template>
        <el-menu-item index="#draw" @click="openDraw">{{ $t('m.Draw_Tool') }}</el-menu-item>
        <el-menu-item index="#math" @click="openMath">{{ $t('m.Math_Toolbox') }}</el-menu-item>
        <el-menu-item index="#visualgo" @click="openVisualgo">&emsp;{{ $t('m.Algorithm_Visualization') }}</el-menu-item>
        <el-menu-item index="#cpp" @click="openCpp">{{ $t('m.Cpp_Online_Editor') }}</el-menu-item>
        <el-menu-item index="#language" @click="changeWebLanguage">{{ $t('m.Change_Language') }}</el-menu-item>
      </el-submenu>
    </el-menu>
    <!-- 移动端悬浮按钮 -->
    <div class="mobile-toggle-btn" v-if="isMobile" @click="toggleTextDisplay">
      <i :class="showText ? 'el-icon-close' : 'el-icon-menu'"></i>
    </div>
    <div class="toggle-button" @click="toggleTextDisplay" v-if="!isMobile">
      <i :class="showText ? 'el-icon-d-arrow-left' : 'el-icon-d-arrow-right'"></i>
    </div>
    <div class="time-display">{{ currentTime }}</div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  name: 'SideNav',
  data() {
    return {
      currentTime: new Date().toLocaleString(),
      timeInterval: null,
      showText: true, // 控制是否显示文字
      isMobile: false // 添加移动端检测
    };
  },
  computed: {
    ...mapGetters(['websiteConfig', 'webLanguage']),
    activeMenuName() {
      if (this.$route.path.split('/')[1] == 'submission-detail') {
        return '/status';
      } else if (this.$route.path.split('/')[1] == 'discussion-detail') {
        return '/discussion';
      }
      return '/' + this.$route.path.split('/')[1];
     }
  },
  mounted() {
    // 从localStorage读取sidebar状态
    const savedState = localStorage.getItem('sidebarCollapsed');
    if (savedState !== null) {
      this.showText = savedState === 'false';
    }
    
    // 检测是否为移动端
    this.checkIsMobile();
    window.addEventListener('resize', this.checkIsMobile);
    
    // 设置时间更新定时器
    this.updateTime();
    this.timeInterval = setInterval(() => {
      this.updateTime();
    }, 1000);
    
    // 添加全局样式表
    const style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = `
      .el-submenu[index="#tool"] .el-menu,
      .el-submenu[index="rank"] .el-menu,
      .side-nav.collapsed .el-submenu[index="#tool"] .el-menu,
      .side-nav.collapsed .el-submenu[index="rank"] .el-menu {
        width: 50px !important;
        min-width: 50px !important;
        max-width: 50px !important;
        position: absolute !important;
        left: 100% !important;
        top: -10px !important;
        margin-left: 10px !important;
        background-color: #f8f9fa !important;
        box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1) !important;
        border-radius: 4px !important;
        z-index: 2000 !important;
      }
      .el-submenu .el-menu.el-menu--popup {
        min-width: auto !important;
        width: auto !important;
        position: absolute !important;
        left: 100% !important;
        top: -10px !important;
        margin-left: 10px !important;
        background-color: #f8f9fa !important;
        box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1) !important;
        border-radius: 4px !important;
        z-index: 2000 !important;
      }
    `;
    document.head.appendChild(style);
    
    // 在组件销毁时移除样式和事件监听
    this.$once('hook:beforeDestroy', () => {
      document.head.removeChild(style);
      window.removeEventListener('resize', this.checkIsMobile);
    });
    
    // 初始设置
    this.$nextTick(() => {
      const toolMenu = document.querySelector('.el-submenu[index="#tool"] .el-menu');
      const rankMenu = document.querySelector('.el-submenu[index="rank"] .el-menu');
      
      if (toolMenu) {
        toolMenu.style.width = this.showText ? '200px' : '64px';
        toolMenu.style.minWidth = this.showText ? '200px' : '64px';
      }
      
      if (rankMenu) {
        rankMenu.style.width = this.showText ? '200px' : '64px';
        rankMenu.style.minWidth = this.showText ? '200px' : '64px';
      }

      // 动态调整特定子菜单箭头的右侧距离
      arrow = document.querySelector('#app > div > div.side-nav > ul > li:nth-child(8) > div > i.el-submenu__icon-arrow.el-icon-arrow-down');
      if (arrow) {
        arrow.style.right = '15px';
      }
      arrow = document.querySelector("#app > div > div.side-nav > ul > li:nth-child(9) > div > i.el-submenu__icon-arrow.el-icon-arrow-down");
      if (arrow) {
        arrow.style.right = '15px';
      }
    });
  },
  beforeDestroy() {
    // 清除时间更新定时器
    clearInterval(this.timeInterval);
  },
  methods: {
    handleMenuSelect(index, indexPath) {
      console.log('Menu item selected:', index, indexPath);
      // 确保路由跳转正常工作
      if (index.startsWith('/')) {
        this.$router.push(index);
      }
      // 在移动端点击菜单项后自动隐藏侧边栏
      if (this.isMobile) {
        this.showText = false;
        localStorage.setItem('sidebarCollapsed', true);
        this.$el.classList.remove('mobile-visible');
        this.$el.classList.add('mobile-hidden');
      }
    },
    // 移动端切换导航显示状态
    toggleMobileNav() {
      this.showText = !this.showText;
      if (this.showText) {
        this.$el.classList.remove('mobile-hidden');
        this.$el.classList.add('mobile-visible');
      } else {
        this.$el.classList.remove('mobile-visible');
        this.$el.classList.add('mobile-hidden');
      }
    },
    checkIsMobile() {
      // 检测屏幕宽度，小于992px认为应该隐藏侧边栏
      this.isMobile = window.innerWidth < 992;
      // 在小屏幕下默认隐藏侧边栏
      if (this.isMobile) {
        this.showText = false;
        this.$el.classList.add('mobile-hidden');
      } else {
        // Optional: restore sidebar visibility if screen is large enough
        this.showText = true;
        this.$el.classList.remove('mobile-hidden');
      };
    },
    watch: {
      showText() {
        this.updateTime();
      }
    },
    updateTime() {
      const now = new Date();
      if (this.showText) {
        const date = now.toLocaleDateString();
        const time = now.getHours().toString().padStart(2, '0') + ':' + 
                    now.getMinutes().toString().padStart(2, '0');
        this.currentTime = date + '\n' + time;
      } else {
        this.currentTime = now.getHours().toString().padStart(2, '0') + ':' + 
                          now.getMinutes().toString().padStart(2, '0');
      }
    },
    openDraw() {
      window.open('https://handraw.top/', '_blank');
    },
    openMath() {
      window.open('https://www.desmos.com/?lang=zh-CN', '_blank');
    },
    openVisualgo() {
      window.open("https://visualgo.net/zh");
    },
    openCpp() {
      window.open("https://csacademy.com/workspace/");
    },
    openCourse() {
      window.open("http://fslong.iok.la:35785/", "_blank");
    },
    changeWebLanguage() {
      this.$store.commit('changeWebLanguage', { language: this.webLanguage == 'zh-CN' ? 'en-US' : 'zh-CN' });
    },
    toggleTextDisplay() {
      console.log('Toggling side nav, current state:', this.showText);
      this.showText = !this.showText;
      // 存储状态到localStorage
      localStorage.setItem('sidebarCollapsed', !this.showText);
      this.updateTime();
      this.$nextTick(() => {
        console.log('Side nav toggled, new state:', this.showText);
      });
    }
  }
}
</script>

<style scoped>
/* 移动端样式优化 */
@media screen and (max-width: 992px) {
  .side-nav {
    transition: transform 0.3s ease;
    z-index: 999;
  }
  
  .side-nav.mobile-hidden {
    transform: translateX(-100%);
  }
  
  .side-nav.mobile-visible {
    transform: translateX(0);
  }
  
  .toggle-button {
    position: fixed;
    left: 10px;
    bottom: 70px;
    z-index: 1000;
    background-color: #2196f3;
    color: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }
  
  /* 移动端悬浮按钮样式 */
  .mobile-toggle-btn {
    position: fixed;
    bottom: 70px;
    left: 55px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #2196f3;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    z-index: 1001;
    cursor: pointer;
    transition: all 0.3s ease;
  }
  
  /* 当侧边栏展开时，将汉堡菜单左边距设置为20px */
  .side-nav.mobile-visible .mobile-toggle-btn {
    left: 30px;
  }
  
  .mobile-toggle-btn:hover {
    background-color: #1976d2;
    transform: scale(1.1);
  }
}

.time-display {
  position: absolute;
  bottom: 5px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #606266;
  padding: 3px;
  background-color: rgba(248, 249, 250, 0.8);
  border-radius: 4px;
  transition: all 0.3s;
  white-space: pre-wrap;
  line-height: 1.2;
  min-height: 30px;
  max-width: calc(100% - 10px);
  text-align: center;
}

.collapsed .time-display {
  font-size: 12px;
}

/* 移动端toggle按钮优化 */
@media screen and (max-width: 992px) {
  .toggle-button {
    position: fixed !important;
    left: 10px !important;
    bottom: 70px !important;
    z-index: 1000;
    background-color: #2196f3;
    color: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }
}

.toggle-button {
  position: absolute;
  bottom: 70px;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
  background-color: #2196f3;
  color: white;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  transition: all 0.3s;
}

.toggle-button:hover {
  background-color: #1976d2;
}
</style>

<style scoped>
/* 强制所有子菜单都使用弹出模式 */
/* 更强制性的样式覆盖 */
.el-menu-vertical .el-submenu .el-menu.always-popup,
.el-menu-vertical .el-submenu .el-menu.always-popup * {
  width: 200px !important;
  min-width: 200px !important;
  max-width: 200px !important;
}

.side-nav:not(.collapsed) .el-submenu .el-menu.always-popup {
  width: 200px !important;
  min-width: 200px !important;
  max-width: 200px !important;
}

.side-nav.collapsed .el-submenu .el-menu.always-popup {
  width: 44px !important;
  min-width:44px !important;
  max-width: 50px !important;
}

/* 菜单项样式 */
.el-menu-vertical .el-submenu .el-menu.always-popup .el-menu-item {
  width: 100% !important;
  min-width: 100% !important;
  max-width: 100% !important;
  margin: 0 !important;
  padding: 0 10px !important;
  box-sizing: border-box !important;
  font-size: 12px !important;
  color: #666 !important;
}

/* 强制覆盖Element UI的默认popper样式 */
.el-popper[x-placement^=right],
.el-popper[x-placement^=right] .el-menu {
  min-width: auto !important;
  width: auto !important;
  max-width: 200px !important;
}

/* 针对tool和rank子菜单的特殊处理 */
.el-submenu[index="#tool"] .el-menu,
.el-submenu[index="rank"] .el-menu,
.el-submenu[index="#tool"] .el-menu *,
.el-submenu[index="rank"] .el-menu * {
  width: 200px !important;
  min-width: 200px !important;
  max-width: 200px !important;
}

.side-nav.collapsed .el-submenu[index="#tool"] .el-menu,
.side-nav.collapsed .el-submenu[index="rank"] .el-menu,
.side-nav.collapsed .el-submenu[index="#tool"] .el-menu *,
.side-nav.collapsed .el-submenu[index="rank"] .el-menu * {
  width: 44px !important;
  min-width: 44px !important;
  max-width: 50px !important;
}

/* 强制覆盖所有子菜单的宽度 */
.el-menu--popup {
  min-width: auto !important;
  width: auto !important;
  max-width: 200px !important;
}

.el-menu--popup .el-menu-item {
  width: 100% !important;
  min-width: 100% !important;
  max-width: 100% !important;
  margin: 0 !important;
  padding: 0 10px !important;
  box-sizing: border-box !important;
  text-align: center !important;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

/* 针对tool和rank子菜单的特殊处理 */
.el-submenu[index="#tool"] .el-menu,
.el-submenu[index="rank"] .el-menu {
  width: 200px !important;
  min-width: 200px !important;
  max-width: 200px !important;
}

.side-nav.collapsed .el-submenu[index="#tool"] .el-menu,
.side-nav.collapsed .el-submenu[index="rank"] .el-menu {
  width: 44px !important;
  min-width: 44px !important;
  max-width: 50px !important;
}

.side-nav {
  height: calc(100vh);
  position: fixed;
  left: 0;
  top: 0px;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  background-color: #f8f9fa;
  z-index: 1000;
  transition: all 0.3s;
  width: 100px;
}

.side-nav.collapsed {
  width: 44px;
}

.side-nav.mobile-hidden {
  transform: translateX(-100%);
}

.side-nav.mobile-visible {
  transform: translateX(0);
}

/* 强制所有状态下submenu都使用弹出式 */
.el-menu-vertical .el-submenu .el-menu {
  position: absolute !important;
  left: 100% !important;
  top: 0 !important;
  margin-left: 10px !important;
  min-width: 100px !important;
  background-color: #f8f9fa !important;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1) !important;
  border-radius: 4px !important;
}

.el-menu-vertical .el-submenu .el-menu-item {
  min-width: 100px !important;
  height: 40px !important;
  line-height: 40px !important;
}

/* 子菜单项在展开时居中 */
.side-nav:not(.collapsed) .el-menu-vertical .el-submenu .el-menu-item {
  text-align: center;
  padding: 0 10px !important;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

/* 确保submenu标题样式一致 */
.el-menu-vertical .el-submenu__title {
  padding: 0 5px 0 5px !important;
}

/* 确保菜单项可点击 */
.el-menu-item, .el-submenu__title {
  pointer-events: auto !important;
  cursor: pointer !important;
  z-index: 1001 !important;
}

/* 确保折叠状态下菜单项仍然可点击 */
.el-menu--collapse .el-menu-item,
.el-menu--collapse .el-submenu__title {
  padding: 0 5px !important;
  overflow: visible;
}

/* 确保菜单项内容可点击 */
.el-menu-item span, .el-submenu__title span,
.el-menu-item i, .el-submenu__title i {
  pointer-events: auto !important;
  position: relative;
  z-index: 1002;
}

/* 展开时图标和文本水平布局 */
.side-nav:not(.collapsed) .el-menu-item i,
.side-nav:not(.collapsed) .el-submenu__title i {
  margin-right: 5px;
  font-size: 16px;
}

.side-nav:not(.collapsed) .el-menu-item span,
.side-nav:not(.collapsed) .el-submenu__title span {
  display: inline-block;
  line-height: normal;
}


.el-menu-vertical {
  border-right: none;
  padding: 0;
}

/* 设置折叠状态下的宽度 */
.el-menu--collapse.el-menu-vertical {
  width: 44px !important;
  min-width: 44px !important;
}

/* 重置所有样式，恢复到基本状态 */
.el-menu-vertical {
  border-right: none;
  padding: 0;
}
/* 基本菜单项样式 */
.el-menu-item, 
.el-submenu__title {
  height: 50px;
  line-height: 50px;
  padding: 0 5px 0 5px !important;
  text-align: left;
}

/* 展开时菜单项水平居中 */
.side-nav:not(.collapsed) .el-menu-item,
.side-nav:not(.collapsed) .el-submenu__title {
  text-align: center;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

/* 特别处理rank和tools菜单 - 使用更精确的选择器 */
.el-menu > .el-submenu[index="#rank"] > .el-submenu__title,
.el-menu > .el-submenu[index="#tool"] > .el-submenu__title {
  padding-left: 0 !important;
}

/* 特别处理rank和tools菜单的图标 */
.el-menu > .el-submenu[index="#rank"] > .el-submenu__title i,
.el-menu > .el-submenu[index="#tool"] > .el-submenu__title i {
  margin-left: 0px !important;
}

/* 箭头位置调整 */
.el-submenu__icon-arrow {
  right: 10px!important;
}

/* 展开时箭头位置调整 */
.side-nav:not(.collapsed) .el-submenu__icon-arrow {
  position: absolute;
  right: 10px !important;
  top: 50%;
  margin-top: -6px;
}

.navbar-icon {
  margin-right: 5px !important;
  width: 24px !important;
  text-align: center !important;
}
.el-submenu {
  margin-left: -15px !important;
  text-align: center !important;
}
.side-nav:not(.collapsed).el-submenu 
{
  margin-left:0px!important;
}
#app > div > div.side-nav > ul > li.el-submenu > ul > li
{
  font-size: 12px;
}
/* 强制调整特定子菜单箭头的右侧距离 */
#app > div > div.side-nav > ul > li:nth-child(8) > div > i.el-submenu__icon-arrow.el-icon-arrow-down {
  right: 0px !important;
}
</style>